package com.tanhua.server.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.SettingsDto;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.SettingsService;
import com.tanhua.server.service.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wjs
 * @version 1.0
 * @date 2021/12/24 0024 下午 4:00
 */
@Service
public class SettingsServiceImpl implements SettingsService {

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SettingsVo settings() {
        //获取userId,mobile
        Long userId = UserHolder.getUserId();
        String mobile = UserHolder.getMobile();

        //创建SettingsVo对象
        SettingsVo vo = new SettingsVo();
        vo.setId(userId);
        vo.setPhone(mobile);

        //根据userId获取Question对象
        Question question = questionApi.findByUserId(userId);
        String txt = question == null ? "请设置问题" : question.getTxt();
        vo.setStrangerQuestion(txt);

        Settings settings = settingsApi.findByUserId(userId);
        if (settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
        }

        return vo;
    }

    @Override
    public void saveQuestions(String content) {
        //获取userId
        Long userId = UserHolder.getUserId();

        Question question = questionApi.findByUserId(userId);

        //判断question是否存在
        if (question == null) {
            //如果不存在,新建添加
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.saveQuestions(question);
        } else {
            //如果存在,更新
            question.setTxt(content);
            questionApi.updateQuestions(question);
        }
    }

    @Override
    public void saveSettings(SettingsDto settingsDto) {
        boolean likeNotification = settingsDto.getLikeNotification();
        boolean pinglunNotification = settingsDto.getPinglunNotification();
        boolean gonggaoNotification = settingsDto.getGonggaoNotification();
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、根据用户id，查询用户的通知设置
        Settings settings = settingsApi.findByUserId(userId);
        //3、判断
        if (settings == null) {
            //保存
            settings = new Settings();
            settings.setUserId(userId);
            settings.setPinglunNotification(pinglunNotification);
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.saveSettings(settings);
        } else {
            settings.setPinglunNotification(pinglunNotification);
            settings.setLikeNotification(likeNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.updateSettings(settings);
        }
    }

    @Override
    public PageResult blacklist(int page, int size) {
        //获取userId
        Long userId = UserHolder.getUserId();

        List<UserInfo> list = blackListApi.blackListPageByUserId(userId, page, size);
        Long count = blackListApi.blackListByUserId(userId);
        PageResult pageResult = new PageResult(page, size, count, list);

        return pageResult;
    }

    @Override
    public void deleteBlackList(Long blackUserId) {
        //获取userId
        Long userId = UserHolder.getUserId();

        blackListApi.deleteBlackList(blackUserId, userId);
    }

    @Override
    public void sendVerificationCode() {
        //获取手机号码
        String mobile = UserHolder.getMobile();
        //1、随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2、调用template对象，发送手机短信
        //template.sendSms(phone,code);
        //3、将验证码存入到redis
        redisTemplate.opsForValue().set("CHECK_CODE2_" + mobile, code, Duration.ofMinutes(5));
    }

    @Override
    public Map checkVerificationCode(String verificationCode) {
        //获取手机号码
        String mobile = UserHolder.getMobile();

        //1、从redis中获取下发的验证码
        String redisCode = (String) redisTemplate.opsForValue().get("CHECK_CODE2_" + mobile);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        boolean verification = true;
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(verificationCode)) {
            //验证码无效
            verification = false;
            throw new RuntimeException("验证码错误");
        }

        Map map = new HashMap();
        map.put("verification",verification);

        return map;
    }

    @Override
    public void updatePhone(String phone) {
//        String mobile = UserHolder.getMobile();
//        User user = userApi.findByMobile(mobile);

        Long userId = UserHolder.getUserId();
        User user = userApi.findByUserId(userId);
        user.setMobile(phone);
        userApi.updateUserById(user);
    }
}
